package com.listeningframework.boot.codegen.generators;

import com.listeningframework.boot.codegen.CodeGenEntity;
import com.listeningframework.boot.codegen.context.MetaContext;
import com.listeningframework.boot.codegen.context.SystemContext;
import com.listeningframework.boot.codegen.exception.BusinessException;
import com.listeningframework.boot.codegen.generators.coders.*;

import java.util.Set;

/**
 * @author lixining
 * @version $Id: GeneratorFactory.java, v 0.1 2016年12月1日 下午7:38:39 lixining Exp $
 * @description GeneratorFactory
 */
public class GeneratorFactory {

    public static GeneratorFactory newinstance() {
        return new GeneratorFactory();
    }

    public void generate() throws BusinessException {
        Set<Class<?>> set = SystemContext.getEntitySet();
        if (set == null || set.isEmpty()) {
            return;
        }
        for (Class<?> clz : set) {
            CodeGenEntity cge = clz.getAnnotation(CodeGenEntity.class);
            if (cge == null || !cge.enabled()) {
                continue;
            }
            MetaContext context = new MetaContext(clz);
            generateSrc(context);
        }
    }

    /**
     * 生成CodeGenEntity源码文件
     *
     * @throws BusinessException
     */
    private void generateSrc(MetaContext context) throws BusinessException {
        // 校验  可用
        if (!context.getCodeGenEntity().enabled()) {
            return;
        }
        context.validate();
        // 1. Controller
        new ControllerCoder(context).writeSrc();
        // 2. Service
        new ServiceCoder(context).writeSrc();
        // 3. Entity
        new EntityCoder(context).writeSrc();
        // 4. Domain
        new ModelCoder(context).writeSrc();
        // 5. Repository
        new RepositoryCoder(context).writeSrc();
        // 6. Mapper
        new MapperCoder(context).writeSrc();
    }

}
